import React from "react";
import CountDown from "@/components/common/countdown"; // 引入封装好的组件

const Emails = () => {
    const [form] = React.UI.Form.useForm();

    // 邮箱认证
    const EmailFinish = async(values:any) => 
    {
        let result = await React.HTTP.post('/business/UserEmail', {
            id: React.Business.id,
            code: values.code
        })
        if (result.code == 0) 
        {
            React.error(result.msg)
            return false
        }
        else
        {
            //提醒
            React.success(result.msg, () => {
                
                //覆盖cookie的信息
                React.Cookie.save('business', result.data)

                //修改一下全局的Business用户数据
                React.Business = result.data
                React.SetBusiness(result.data)

                //返回上一个界面
                React.navigate(-1)
            })
        }
    };

    // 发送验证码
    const SendEmail = async() =>
    {
        let result = await React.HTTP.post('/business/UserEmail', {
            id: React.Business.id,
            action: 'send'
        })
        if (result.code == 0) 
        {
            React.error(result.msg)
            return false
        }
        else
        {
            React.success(result.msg)
        }
    }

    return (
        <>
            <React.UI.Form
                form={form}
                onFinish={EmailFinish}
                layout="horizontal"
                footer={
                    <React.UI.Button block type="submit" color="primary" size="large">
                        提交
                    </React.UI.Button>
                }
            >
                <React.UI.Form.Item
                    initialValue={React.Business.email}
                    rules={[
                        { required: true, message: "请填写正确的邮箱" },
                        { type: "email", warningOnly: true },
                    ]}
                    name="email"
                    label="邮箱"
                >
                    <React.UI.Input placeholder="请输入邮箱" />
                </React.UI.Form.Item>

                <React.UI.Form.Item
                    label="邮箱验证码"
                    extra={
                        <CountDown
                            initialSeconds={60}
                            buttonTextBefore="发送验证码"
                            SendEmail={SendEmail}
                        />
                    }
                    name="code"
                    rules={[{ required: true, message: "验证码不能为空" }]}
                >
                    <React.UI.Input placeholder="请输入邮箱验证码" />
                </React.UI.Form.Item>
            </React.UI.Form>
        </>
    );
};

export default Emails;